#include "common/http/HttpRequest.h"
#include "common/http/HttpAgent.h"

#include "common/log/log.h"

#include <iostream>
using namespace std;

HttpRequest::HttpRequest()
    : method_(kGet)
    , version_(kHttp11) {}

HttpRequest::HttpRequest(std::string query)
    : method_(kGet)
    , version_(kHttp11)
    , query_(query) {}

HttpRequest::HttpRequest(Method method, Version version, std::string query)
    : method_(method)
    , version_(version)
    , query_(query) {}

HttpRequest::~HttpRequest() {}

bool HttpRequest::setHeader(Header headerName, std::string value) {
    switch (headerName) {
    case kHost:
        headers_.insert(std::make_pair("Host", value));
        break;
    case kUserAgent:
        headers_.insert(std::make_pair("User-Agent", value));
        break;
    case kAccept:
        headers_.insert(std::make_pair("Accept", value));
        break;
    default:
        ERROR_LOG("HttpRequest::setHeader():unknown header");
        return FAILED;
    }
    return SUCCESSFUL;
}

std::string HttpRequest::packageSendData() {
    std::string data = "";
    if (!methodParse(data)) {
        data.clear();
        return data;
    }
    data += " ";
    data += query_;
    data += " ";
    if (!versionParse(data)) {
        data.clear();
        return data;
    }
    data += CRLF;
    packageHeaders(data);
    data += CRLF;
    return data;
}

// =============== private ====================

bool HttpRequest::methodParse(std::string &data) {
    switch (method_) { // kInvalid, kGet, kPost, kHead, kPut, kDelete
    case kGet:
        data += "GET";
        break;
    case kPost:
        data += "POST";
        break;
    case kHead:
        data += "HEAD";
        break;
    case kPut:
        data += "PUT";
        break;
    case kDelete:
        data += "DELETE";
        break;
    case kInvalid:
        ERROR_LOG("HttpRequest::methodParse():kInvalid");
        return false;
    default:
        ERROR_LOG("HttpRequest::methodParse():Unknown");
        return false;
    }
    return true;
}

bool HttpRequest::versionParse(std::string &data) {
    switch (version_) { // kUnknown, kHttp10, kHttp11
    case kHttp10:
        data += "HTTP/1.0";
        break;
    case kHttp11:
        data += "HTTP/1.1";
        break;
    case kUnknown:
        ERROR_LOG("HttpRequest::versionParse():kUnknown");
        return false;
    default:
        ERROR_LOG("HttpRequest::versionParse():kInvalid");
        return false;
    }
    return true;
}

void HttpRequest::packageHeaders(std::string &data) {
    for (auto it : headers_) {
        data += it.first;
        data += ":";
        data += it.second;
        data += CRLF;
    }
}